import { ref, watchEffect } from 'vue';
import { getNetworkType } from '../utils/uni-promise';

export const isConnectedRef = ref(undefined);
export const useNetWorkHook = () => {
	watchEffect(() => {
		if (typeof isConnectedRef.value === 'boolean' && !isConnectedRef.value) {
			uni.showToast({ title: '网络跑小差啦~', icon: 'none' });
		}
	});
	const callBack = (res : UniNamespace.OnNetworkStatusChangeSuccess) => {
		isConnectedRef.value = res.isConnected;
	};

	const subscriptionNetworkStatusChange = () => {
		uni.onNetworkStatusChange(callBack);
	};
	const offNetworkStatusChange = () => {
		uni.offNetworkStatusChange(callBack);
	};

	const checkNetworkStatus = async () => {
		if (typeof isConnectedRef.value === 'undefined') {
			const result : UniNamespace.GetNetworkTypeSuccess = await getNetworkType();
			isConnectedRef.value = result.networkType !== 'none';
		}
	};

	const setNetWorkOffline = () => {
		isConnectedRef.value = undefined;
		isConnectedRef.value = false;
	};

	const setNetWorkStatusToDefault = () => {
		isConnectedRef.value = undefined;
	};

	const checkNetWorkOffline = async () => {
		if (typeof isConnectedRef.value === 'undefined') {
			await checkNetworkStatus();
		}

		if (!isConnectedRef.value) {
			setNetWorkOffline();
		}
		return isConnectedRef.value;
	};

	return { subscriptionNetworkStatusChange, offNetworkStatusChange, setNetWorkOffline, checkNetworkStatus, setNetWorkStatusToDefault, checkNetWorkOffline };
};